<?php

namespace backend\models\form;

use backend\models\AdminUser;
use common\service\ConstatService;
use yii\base\Model;
use common\service\BaseToolService;
use Yii;

/**
 *  登陆表单
 */
class LoginForm extends Model {
    
    const ADMIN_USER = 2 ;

    public $username;
    public $password;
    public $rememberMe = true;
    private $_user = false;
//    public $verifyCode;

    /**
     * @inheritdoc
     */
    public function rules() {
        return [
            [['username', 'password'], 'filter', 'filter' => 'trim'],
            [['username', 'password'], 'required'],
            [['username', 'password'], 'string', 'min' => 1],
            ['password', 'validatePassword'],
//            ['verifyCode', 'captcha','captchaAction'=>'/login/captcha'],
        ];
    }

    public function attributeLabels() {
        return [
            'username'=>'用户名',
            'password'=>'密码',
//            'verifyCode'=>'验证码',
        ] ;
    }

    public function validatePassword() {
        $user = $this->getUser();
        if (empty($user)) {
            $this->addError("username", "用户不存在");
            return false;
        }

        if($user->login_error == 5 && (time()-strtotime($user->login_date) < 30*60)){
            $this->addError("username", "连续输入错误5次，请30分钟后再试");
            return false;
        }
        if (BaseToolService::encodePassword($user->password_order, $this->password) !== $user->password) {
            if($user->login_error == 5 && (time()-strtotime($user->login_date) > 30*60)){
                $user->login_error = 0;
                $user->save();
            }
            $this->addError("password", "你还剩下".(5-($user->login_error+1))."次机会，密码错误次数超过5次，账户会被锁定30分钟");
            $user->login_date = date('Y-m-d H:i:s');
            $user->login_error += 1;
            $user->save();
            return false;
        }
        if ($user->status == 0) {
            $this->addError("username", "账户已停用");
            return false;
        }
    }

    public function login() {
        if ($this->validate()) {
            $this->getUser()->login_error = 0;
            $this->getUser()->save();
            return Yii::$app->admin->login($this->getUser(), $this->rememberMe ? 3600 * 24 * 1 : 0);
        } else {
            return false;
        }
    }

    public function getUser() {
        if ($this->_user === false) {
            $this->_user = AdminUser::findOne(["username"=>$this->username]);
        }
        return $this->_user;
    }

}
